﻿CREATE PROCEDURE [acms].[UserRole_Put]
	@Id int, 
	@UserId int,
	@RoleId int,
	@SiteId int,
	@Created datetime,
	@Start datetime,
	@End datetime,
	@ConcurencyId rowversion,
	@IdOut int output, 
    @UserNameOut VarChar(50) output,
    @FirstNameOut VarChar(50) output,
    @LastNameOut VarChar(50) output,
    @RoleNameOut VarChar(100) output,
    @IsAdminRoleOut Bit output,
	@ConcurencyIdOut rowversion output
AS
	if @Id is null or @Id = 0 begin
		insert into UserRole
			(UserId, RoleId, SiteId, Created, Start, [End])
		values
			(@UserId, @RoleId, @SiteId, @Created, @Start, @End)
		set @IdOut = @@Identity
	end
	else if exists (Select null from UserRole_View Where Id = @Id and ConcurencyId = @ConcurencyId) begin
		update UserRole
		set
			UserId = @UserId, 
			RoleId = @RoleId, 
			SiteId = @SiteId, 
			Start = @Start, 
			[End] = @End
		Where Id = @Id and ConcurencyId = @ConcurencyId
		set @IdOut = @Id
	end
	else if exists (Select null from UserRole_View Where Id = @Id)
		return -100
	else
		return -200
		
	select @UserNameOut = UserName, @FirstNameOut = FirstName, @LastNameOut = LastName, @RoleNameOut = RoleName, @IsAdminRoleOut = IsAdminRole, @ConcurencyIdOut = ConcurencyId from UserRole_View where Id = @IdOut
	
RETURN 0;